package com.community.controller;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.exceptions.ClientException;
import com.community.entity.Order;
import com.community.entity.ProblemUser;
import com.community.entity.Student;
import com.community.entity.StudentCollection;
import com.community.service.*;
import com.community.util.*;
import com.community.util.wechat.WechatService;
import com.feng.fengDUtil.Page;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.*;

/**
 * 需求登录才能访问的接口
 */
@RestController
@RequestMapping(value = "/auth")
@Log4j2
public class WxAuthAction {
    @Autowired
    private QuizService quizService;

    @Autowired
    private StudentService studentService;

    @Autowired
    private MajorService majorService;
    @Autowired
    private OrderService orderService;

    @Autowired
    private DictService dictService;

    @Autowired
    private WechatService wechatService;


    @RequestMapping(value = "/userInfo")
    public Result userInfo() {

        JSONObject obj = new JSONObject();
        obj.put("userInfo",studentService.curStudent());
        obj.put("allDict",dictService.allDict());
        return Result.success(obj);
    }

    @RequestMapping(value = "/vipViaCode")
    public Result vipViaCode(String code) {
        Student student = studentService.curStudent();
        if(student.getVip_level()!=null && student.getVip_level()>0){
            return Result.success("您已经是vip会员了!");
        }
        try {
            studentService.vipViaCode(student,code);
            return Result.success(student);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    @ResponseBody
    @RequestMapping("sendSmsForChange")
    public Result sendSmsForChange(@RequestParam String phone,HttpSession session)  {
        Date sendSmsForChangeTime = (Date)session.getAttribute("sendSmsForChangeTime");
        if(sendSmsForChangeTime!=null && sendSmsForChangeTime.after(new Date())){
            return Result.error("1分钟内已发送过验证码，请稍候！");
        }
        Student student = studentService.findStudent(phone);
        if(student !=null){
            return Result.error("此手机号已注册,请直接登录！");
        }

        sendSmsForChangeTime = DateUtils.getTimeByMinute(1);
        session.setAttribute("sendSmsForChangeTime",sendSmsForChangeTime);
        String verifyCode = (Math.random()+"").substring(2,8);
        try {
            MessageUtil.message(phone, verifyCode);
            session.setAttribute("verifyCodeForChange",verifyCode+"#"+phone);
            return Result.success();
        } catch (ClientException e) {
            e.printStackTrace();
            return Result.error(e.getErrMsg());
        }
    }

    @ResponseBody
    @PostMapping("changePhone")
    public Result changePhone(@RequestParam String username,@RequestParam String verifyCode,HttpSession session)  {

        String verifyCodeForChange = (String)session.getAttribute("verifyCodeForChange");
        if(verifyCodeForChange==null || !(verifyCode+"#"+username).equalsIgnoreCase(verifyCodeForChange)){
            return Result.error("验证码错误！");
        }
        Student student = studentService.curStudent();
        student.setUsername(username);
        studentService.update(student);
        return Result.success(student);
    }

    /**
     * 获取获取用户的题
     * @return
     */
    @RequestMapping(value = "/quiz")
    public Result quiz(Integer gtype) {
            Student student = SessionUtil.getCurStudent();
        List<ProblemUser> list = quizService.allProblems(student,gtype);
     //   list.forEach(n->n.parseOptions());
        JSONObject ret = new JSONObject();
        ret.put("questions",list);
        long notAnswered = list.stream().filter(n-> StringUtils.isEmpty(n.getResult())).count();
        if(notAnswered == 0){
            quizService.analysis(list,ret);
        }
        return Result.success(ret);
    }

    @RequestMapping(value = "/answer")
    public Result answer(@RequestBody List<ProblemUser> answers) {
        for (ProblemUser answer: answers){
            answer.setUid(SessionUtil.getCurStudentId());
        }
        quizService.saveOrUpdateAll(answers);
        JSONObject ret = new JSONObject();
        ret.put("questions",answers);

        quizService.analysis(answers,ret);
        return Result.success(ret);
    }

    @PostMapping(value = "/saveScore")
    public Result saveScore(@RequestBody Student student) {
        studentService.updateWithoutNull(student);
        return Result.success(studentService.curStudent());
    }

    @RequestMapping(value = "/overview")
    public Result overview(@RequestParam Integer year, Search search) {

        Student student = studentService.curStudent();
        search.setSelectSubjects(student.getSelect_subject().split(","));
        search.setBatch(Optional.ofNullable(search.getBatch()).orElse(1));
        Map map = new HashMap();
        map.put("total",majorService.statics(year,search.getBatch()));
        map.put("majorFit",majorService.statics(year,search));
        return Result.success(map);
    }

    @RequestMapping(value = "/gradeRet")
    public Result gradeRet(@RequestParam Integer year, Search search) {

        Student student = studentService.curStudent();
        search.setSelectSubjects(student.getSelect_subject().split(","));
        return Result.success(majorService.statics(year,search));
    }

    @RequestMapping(value = "/largeClass")
    public Result largeClass(@RequestParam Integer year, Search search) {
        Student student = studentService.curStudent();
        search.setSelectSubjects(student.getSelect_subject().split(","));
        return Result.success(majorService.largeClass(year,search));
    }

    @RequestMapping(value = "/queryMajor")
    public Result queryMajor(Page<Map> page, Search search) {
        Student student = studentService.curStudent();
        search.setStudentId(student.getId());
        search.setSelectSubjects(student.getSelect_subject().split(","));
        majorService.query(page,search);
        page.getData().forEach(n->majorService.getChance(student.getRankNum(),n));
        return Result.success(page);
    }

    @RequestMapping(value = "/saveCollection")
    public Result saveCollection(@RequestBody StudentCollection bean) {
        bean.setUser_id(SessionUtil.getCurStudentId());
        majorService.saveCollection(bean);
        return Result.success();
    }

    @RequestMapping(value = "/delCollection")
    public Result delCollection(String major_id) {
        majorService.delCollection(major_id);
        return Result.success();
    }

    @RequestMapping(value = "/getOrder")
    public Result getOrder() {
        return Result.success(orderService.getOrder(SessionUtil.getCurStudentId()));
    }

    @PostMapping(value = "/saveOrder")
    public Result saveOrder(@RequestBody Order order) {
        order.setStudentId(SessionUtil.getCurStudentId());
        order.setCreateDate(new Date());
        orderService.saveOrUpdate(order);
        return Result.success();
    }

    @RequestMapping(value = "/uploadIntentions", method = RequestMethod.POST)
    public Result uploadIntentions(MultipartFile file){
        try {
            return Result.success(majorService.uploadIntentions(file,studentService.curStudent()));
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    @ResponseBody
    @RequestMapping("prepay")
    public Map<String, String> vipPay(HttpServletRequest request) {
        // 获取H5页面调起微信支付页面所需的配置信息
        SortedMap ret = new TreeMap<String, String>();
        try {
            Student student = studentService.curStudent();
            if (student.getVip_level()!=null && student.getVip_level()>0) {
                ret.put("msg", "已经是vip,无需充值！");
                ret.put("code", "-1");
                return ret;
            }
            //支付金额
            BigDecimal totalFee = new BigDecimal(380);
            //写预支付业务表
            String orderId = wechatService.getOrderIdByTime();

            studentService.saveVipOrder(student,totalFee,orderId);

            //获取预支付信息
            Map<String, String> prepayMap = wechatService.getPrepayInfo(student.getOpen_id(),"金榜高考-VIP充值",orderId,"38000",request.getRemoteAddr());
            // 公众账号appId
            ret.put("appId", wechatService.appid);
            // 时间戳
            ret.put("timeStamp", wechatService.createTimestamp());
            // 随机字符串
            ret.put("nonceStr", wechatService.getNonceStr());
            // 预支付Id
            ret.put("package", "prepay_id=" + prepayMap.get("prepay_id"));
            // 签名方式
            ret.put("signType", "MD5");
            // 第二次签名，生成支付签名，供前台js调用微信支付用，共5个参数
            String paySign = wechatService.getSign(ret);
            // packageValue，是方便ajax传值到页面中package是js的关键字出错
            ret.put("packageValue", "prepay_id=" + prepayMap.get("prepay_id"));
            // 支付签名
            ret.put("paySign", paySign);
            ret.put("msg", prepayMap.get("return_msg"));                                               //paySign的生成规则和Sign的生成规则一致
            ret.put("code", prepayMap.get("return_code"));

        } catch (Exception e) {
            e.printStackTrace();
            ret.put("code", "-1");
            ret.put("msg", "系统异常");
        }
        return ret;
    }

}
